global root_dir = "`1'"

include "$root_dir/code/config/config.do"

cap noi log using ${log_dir}/table_A14_lags_leads_horserace.log, replace name(tabl)

capture noi {
    
    * v6

    ** Prep Data

    use ${final_dir}/regression_dataset_from1970_tfacit1.dta, clear

    tab year, gen(YY_)

    clonevar stockown = k${depvar}_${ttt} 
    clonevar stockownzero = k${depvar}_${ttt}0 
    clonevar stockother = kNOT_${depvar}_${ttt} 
    clonevar stockotherzero = kNOT_${depvar}_${ttt}0	
    clonevar LSW_l2 = lswMPm_1995_a
    clonevar HSW_l2 = hswMPm_1995_a
    clonevar VAEMP = vaempMPm_1995_a
    clonevar GDPGAP = lngdpgap_1995_a	
    foreach shr in shr4 {
        clonevar VAEMP_foreign = vaempMPm_`shr'_foreign_1995_a
        clonevar LSW_foreign_l2 = lswMPm_`shr'_foreign_1995_a
        clonevar HSW_foreign_l2 = hswMPm_`shr'_foreign_1995_a
        clonevar GDPGAP_foreign = lngdpgap_shr_foreign_1995_a	
    }
    clonevar spilloversown = spill${depvar}${ttt}_1995_a
    clonevar spilloversother = spillN${depvar}${ttt}_1995_a
    clonevar spilloversownzero = spill${depvar}${ttt}_1995_a0
    clonevar spilloversotherzero = spillN${depvar}${ttt}_1995_a0
    sort lse_id year
    xtset lse_id year

    egen yearctryindustry = group(year industry country_shr_1995) if year <= 2009
    egen yearctry = group(year country_shr_1995) if year <= 2009
    egen yearindustry = group(year industry) if year <= 2009

    bys lse_id: egen _total_${depvar}_${ttt}_1995 = sum(${depvar}_${ttt}) if year>=1995+2 & year <= 2009+2
    bys lse_id: egen total_${depvar}_${ttt}_1995 = max(_total_${depvar}_${ttt}_1995)
    drop _total_${depvar}_${ttt}_1995


    global pdef "pauto90"
    gen arcsinh_${pdef} = log(${pdef}_${ttt}+((${pdef}_${ttt})^2+1)^(1/2))
    gen F2_arcsinh_${pdef} = F2.arcsinh_${pdef}
    local pauto "F2_arcsinh_${pdef}"

    ****

    qui do ${code_dir}/config/tabletools.do

    ** RUN REGS

    foreach foreign in "domfor" "_foreign" { 
        if "`foreign'" == "domfor" {
            local foreign ""
        }
        estimates clear
        *define the leads and lags per column
        forvalues lead_vm = -6(1)2 { 
            if `lead_vm' == -6 {
                local adjm "-6"
                local leadm "L4."
                local leadnm "L4"
                local col = 1
            }
            if `lead_vm' == -5 {
                local adjm "-5"
                local leadm "L3."
                local leadnm "L3"
                local col = 2
            }
            if `lead_vm' == -4 {
                local adjm "-4"
                local leadm "L2."
                local leadnm "L2"
                local col = 3
            }
            if `lead_vm' == -3 {
                local adjm "-3"
                local leadm "L1."
                local leadnm "L1"
                local col = 4
            }
            if `lead_vm' == -2 {
                local adjm "-2"
                local leadm ""
                local leadnm ""
                local col = 5
            }
            if `lead_vm' == -1 {
                local adjm "-1"
                local leadm "F1."
                local leadnm "F1"
                local col = 6
            }
            if `lead_vm' == 0 {
                local adjm "0"
                local leadm "F2."
                local leadnm "F2"
                local col = 7
            }
            if `lead_vm' == 1 {
                local adjm "+1"
                local leadm "F3."
                local leadnm "F3"
                local col= 8
            }
            if `lead_vm' == 2 {
                local adjm "+2"
                local leadm "F4."
                local leadnm "F4"
                local col = 9
            }

            gen LSW`foreign'_lj = `leadm'LSW`foreign'_l2 
            gen HSW`foreign'_lj = `leadm'HSW`foreign'_l2
            gen GDPGAP`foreign'_lj = `leadm'GDPGAP`foreign'
            gen VAEMP`foreign'_lj = `leadm'VAEMP`foreign'

            if `lead_vm' != -2 { 
                ppmlhdfe F2.${depvar}_${ttt} `pauto' LSW`foreign'_l2 HSW`foreign'_l2 GDPGAP`foreign' VAEMP`foreign' LSW`foreign'_lj HSW`foreign'_lj GDPGAP`foreign'_lj VAEMP`foreign'_lj stockown stockownzero stockother stockotherzero spilloversown spilloversownzero spilloversother spilloversotherzero  if year>=1995 & maxweight_1995 < 1 & missing_weights_1995==0 & missing_spill_weights_1995 == 0 & total_${depvar}_${ttt}_1995>0,vce(cluster lse_id) absorb(lse_id yearindustry yearctry)
            }
            else {
                ppmlhdfe F2.${depvar}_${ttt} `pauto' LSW`foreign'_l2 HSW`foreign'_l2 GDPGAP`foreign' VAEMP`foreign' stockown stockownzero stockother stockotherzero spilloversown spilloversownzero spilloversother spilloversotherzero  if year>=1995 & maxweight_1995 < 1 & missing_weights_1995==0 & missing_spill_weights_1995 == 0 & total_${depvar}_${ttt}_1995>0,vce(cluster lse_id) absorb(lse_id yearindustry yearctry)
            }

            estadd local f "\yes"
            estadd local iy "\yes"
            estadd local cy "\yes"
            estadd local has_stockspill "\yes"
            estadd local has_vaemp "\yes"
            estadd local has_gdpgap "\yes"
            estadd local obs "{\num{`e(N)'}}"
            estadd local firms "{\num{`e(N_clust)'}}"

            estimates store col`col'
            drop *_lj 
        }
        setlabels
        dhoztab col1 col2 col3 col4 col5 col6 col7 col8 col9 using ${tab_dir}/appendix/Table_A14_leadslags_horserace`foreign'`pauto'.tex,  b(%10.2f) se(%10.2f) nogaps replace showdepvarinfo numbers nonotes nolines nomtitles sfmt(a1) scalars("has_gdpgap \noalign{\medskip} GDP gap" "has_vaemp Labor productivity" "has_stockspill Stocks and spillovers" "f Firm fixed effects" "iy Industry \stimes year fixed effects" "cy Country \stimes year fixed effects" "obs \noalign{\medskip} Observations"  "firms Number of firms") label drop(*zero _cons stock* spill* GDPGAP* VAEMP*) noobs rename(LSW_foreign_l2 LSW_l2 HSW_foreign_l2 HSW_l2 GDPGAP_foreign GDPGAP VAEMP_foreign VAEMP GDPPC_foreign GDPPC LSWHSW_foreign LSWHSW LSW_foreign_lj LSW_lj HSW_foreign_lj HSW_lj GDPGAP_foreign_lj GDPGAP_lj VAEMP_foreign_lj VAEMP_lj F2_arcsinh_pauto90 Arcsinhpauto90) /// TODO: remove the arcsinhpauto's 
        order(LSW_l2 LSW_lj HSW_l2 HSW_lj) ///
        rawaddheader(Macrovars lag j & {6} & {5} & {4} & {3} & {2} & {1} & {0} & {-1} & {-2} \\ \cmidrule(lr){2-10}) /// 
        depvar("Auto95") ///
        notes("This table studies different timing assumptions. The independent variables are included twice: lagged by two periods (baseline) and shifted as indicated by lag j in the header. The positive numbers are lags, the negative numbers indicate leads in years. All columns include controls for labor productivity and the business cycle, firm and industry-year fixed effects, and country-year fixed effects. In Panel B, the macroeconomic variables are the previously defined normalized foreign variables. Standard errors are clustered at the firm-level and reported in parentheses.")
    }

    * combined manually to table_leadslags_horserace_panel.tex 


}
if _rc == 0 {
    display "Execution finished successfully."
}
else {
    display "Execution finished with errors."
}